<template>
  <n-modal
    v-model:show="getProps.modalData.show"
    class="custom-card m-ad-template-media-select"
    preset="card"
    :mask-closable="false"
    :title="'创建定向包'"
    :style="{ width: '800px' }"
    :bordered="false"
    :segmented="{
      content: 'hard',
      footer: 'hard'
    }"
  >
    <x-form ref="formRef" v-model:model="formData" :rules="rules" label-placement="left" label-width="150">
      <n-form-item label="定向包名称" path="targetName">
        <n-input v-model:value="formData.targetName" placeholder="请输入定向包名称" maxlength="50" show-count />
      </n-form-item>
      <n-form-item label="地域" :show-require-mark="true">
        <n-radio-group value="1">
          <n-radio-button value="1">排除新疆、西藏、港澳台</n-radio-button>
        </n-radio-group>
      </n-form-item>
      <n-form-item label="年龄" :show-require-mark="true">
        <div class="flex">
          <n-select
            v-model:value="formData.minAge"
            :options="minAgeList"
            label-field="label"
            value-field="value"
            :render-label="renderAgeMinLabel"
            filterable
            style="width: 200px"
          />
          <n-text style="margin: 0 10px">至</n-text>
          <n-select
            v-model:value="formData.maxAge"
            :options="maxAgeList"
            label-field="label"
            value-field="value"
            :render-label="renderAgeLabel"
            filterable
            style="width: 200px"
          />
        </div>
      </n-form-item>
      <n-form-item label="性别" :show-require-mark="true">
        <n-radio-group v-model:value="formData.gender">
          <n-radio-button
            v-for="item in dictionary['ENG_GENDER']"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </n-radio-group>
      </n-form-item>
      <n-form-item label="排除已转化用户" :show-require-mark="true">
        <n-radio-group v-model:value="formData.excludedDimension">
          <n-radio-button
            v-for="item in dictionary['ENG_EXCLUDED_DIMENSION']"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </n-radio-group>
      </n-form-item>
      <n-form-item label="定向人群">
        <n-select
          v-model:value="formData.customAudience"
          :options="audienceList"
          label-field="audienceName"
          value-field="audienceId"
          multiple
          filterable
          @update:value="customAudienceUpdate"
        />
      </n-form-item>
      <n-form-item label="排除人群">
        <n-select
          v-model:value="formData.excludedCustomAudience"
          :options="audienceListExcluded"
          label-field="audienceName"
          value-field="audienceId"
          multiple
          filterable
          @update:value="excludedCustomUpdate"
        />
      </n-form-item>
      <n-space justify="center">
        <x-button @click="getProps.modalData.show = false">取消</x-button>
        <x-button :loading="saveLoading" type="primary" @click="handleSavePackage">保存</x-button>
      </n-space>
    </x-form>
  </n-modal>
</template>

<script setup lang="ts">
  import { XForm, XButton } from '@/components'
  import { NFormItem, NSpace, NModal, NSelect, NText, NRadioGroup, NRadioButton, NInput, useMessage } from 'naive-ui'
  import { computed, h, onMounted, reactive, ref } from 'vue'
  import { useStore } from '@/store'
  import { EditOutlined } from '@vicons/antd'
  import { useDictionary } from '@/hooks'
  const { get: getDict, find: findDict } = useDictionary()
  const dictionary = computed(() => store.getters.dictionary)
  const message = useMessage()
  const store = useStore()
  const emit = defineEmits(['success'])
  const props = defineProps({
    modalData: {
      type: Object,
      default: () => {}
    },
    accountCode: {
      type: String,
      default: ''
    }
  })
  const getProps = reactive(props)
  const formRef = ref()
  const formData = ref({
    accountCode: getProps.accountCode,
    targetName: null,
    minAge: null,
    maxAge: null,
    gender: -1,
    excludedDimension: -1,
    customAudience: [],
    excludedCustomAudience: []
  })
  const rules = reactive({
    targetName: [
      {
        required: true,
        type: 'string',
        message: '请输入定向名称',
        trigger: 'blur'
      }
    ]
  })
  const saveLoading = ref(false)
  let minAge = []
  for (let i = 14; i < 67; i++) {
    minAge.push({
      label: i >= 66 ? '66岁及以上' : i + '岁',
      value: i,
      disabled: [15, 16, 17].includes(i)
    })
  }
  let maxAge = []
  for (let i = 18; i < 67; i++) {
    maxAge.push({
      label: i >= 66 ? '66岁及以上' : i + '岁',
      value: i
    })
  }
  const minAgeList = minAge
  const maxAgeList = maxAge
  const audienceList = ref([])
  const audienceListExcluded = ref([])
  onMounted(() => {
    getDict('ENG_GENDER,ENG_EXCLUDED_DIMENSION')
    getAdsAudienceList()
  })
  function renderAgeLabel(option: any) {
    option.value < formData.value.minAge ? (option.disabled = true) : (option.disabled = false)
    return option.label
  }
  function renderAgeMinLabel(option: any) {
    if (formData.value.maxAge) {
      option.value > formData.value.maxAge
        ? (option.disabled = true)
        : [15, 16, 17].includes(option.value)
        ? (option.disabled = true)
        : (option.disabled = false)
    }
    return option.label
  }
  function customAudienceUpdate(val: any) {
    audienceListExcluded.value.forEach((item) => {
      if (val.includes(item.audienceId)) {
        item.disabled = true
      } else {
        item.disabled = false
      }
    })
  }
  function excludedCustomUpdate(val: any) {
    audienceList.value.forEach((item) => {
      if (val.includes(item.audienceId)) {
        item.disabled = true
      } else {
        item.disabled = false
      }
    })
  }
  async function getAdsAudienceList() {
    const { data } = await store.dispatch('intelligent/getAdsAudienceList', {
      accountCode: formData.value.accountCode,
      type: 1
    })
    audienceList.value = data || []
    audienceListExcluded.value = JSON.parse(JSON.stringify(data)) || []
  }

  function validateForm() {
    return new Promise<void>((resolve, reject) => {
      formRef.value?.validate(async (errors: any) => {
        if (!errors) {
          try {
            resolve()
          } catch (e) {
            reject()
          }
        } else {
          reject()
          console.log('errors', errors)
        }
      })
    })
  }
  // 修改投放方式
  async function handleSavePackage() {
    await validateForm()
    if (!formData.value.minAge || !formData.value.maxAge) {
      message.warning('请选择年龄范围')
      return
    }
    const params = {
      accountCode: formData.value.accountCode,
      targetName: formData.value.targetName,
      gender: formData.value.gender,
      minAge: formData.value.minAge,
      maxAge: formData.value.maxAge,
      excludedDimension: formData.value.excludedDimension,
      customAudience: formData.value.customAudience,
      excludedCustomAudience: formData.value.excludedCustomAudience
    }
    saveLoading.value = true
    store
      .dispatch('intelligent/targetingsAdd', params)
      .then(() => {
        message.success('添加成功')
        getProps.modalData.show = false
        emit('success')
      })
      .catch(() => {
        saveLoading.value = false
      })
  }
</script>

<style scoped lang="scss"></style>
